﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Manager;

public class SceneView : ViewBase {

    //场景全局依赖关系
    private AssetBundleManifest SceneGlobalManifest;
    //场景名
    private string sceneName;
    //场景需要加载的AB列表
    private List<string> sceneABList = new List<string>();
    //场景配置数据
    private SceneFormatVo sceneFormatVo;
    //当前位置
    private Vector3 defPos;
    //当前加载已经加载完成的子场景列表
    private List<string> subSceneList = new List<string>();
    //配置场景名
    private string configSceneName;
    //当前是否在加载中
    private bool isLoadMainScene = false;
    //当前是否在加载子场景
    private bool isLoadSubScene = false;

    private bool Running = false;
	private float Speed = 10;

	protected override void Start () {
        base.Start();
	}

    private Vector3 cameraPos;
    void Update()
    {
        //测试动态加载
		if (Input.GetKey (KeyCode.A)) {
			if (Camera.main != null) {
				cameraPos = Camera.main.transform.position;
				cameraPos += Vector3.left * Speed * Time.deltaTime;
				Camera.main.transform.position = cameraPos;

				if (SceneHero.instance != null) {
					SceneHero.instance.Walk (Vector3.left,Speed);
				}
                Running = true;
            }
		} else if (Input.GetKey (KeyCode.D)) {
			if (Camera.main != null) {
				cameraPos = Camera.main.transform.position;
				cameraPos += Vector3.right * Speed * Time.deltaTime;
				Camera.main.transform.position = cameraPos;
				if (SceneHero.instance != null) {
					SceneHero.instance.Walk (Vector3.right,Speed);
				}
                Running = true;
            }
		} else if (Input.GetKey (KeyCode.W)) {
			if (Camera.main != null) {
				cameraPos = Camera.main.transform.position;
				cameraPos += Vector3.forward * Speed * Time.deltaTime;
				Camera.main.transform.position = cameraPos;
				if (SceneHero.instance != null) {

					SceneHero.instance.Walk (Vector3.forward,Speed);
				}
                Running = true;
            }
		} else if (Input.GetKey (KeyCode.S)) {
			if (Camera.main != null) {
				cameraPos = Camera.main.transform.position;
				cameraPos += Vector3.back * Speed * Time.deltaTime;
				Camera.main.transform.position = cameraPos;

				if (SceneHero.instance != null) {
					SceneHero.instance.Walk (Vector3.back,Speed);
				}
                Running = true;
            }
		}
        else
        {
            if (Running)
            {
                if (SceneHero.instance != null)
                    SceneHero.instance.Stop();
                Running = false;
            }
        }

        if (Camera.main != null)
        {
            if(sceneFormatVo != null && !isLoadSubScene && !isLoadMainScene)
                UpdatePos(Camera.main.transform.position);
        }
    }

    private void InitScene()
    {
        if (SceneGlobalManifest == null)
        {
            AssetBundle SceneGlobalDependencies = GameManager.instance.resourceManager.GetAssetBundle("SceneGlobalDependencies");
            SceneGlobalManifest = SceneGlobalDependencies.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
            GameManager.instance.resourceManager.RemoveAssetBundle("SceneGlobalDependencies",false);
        }
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
    }

    //卸载当前场景
    private void UnLoadScene()
    {
        if (sceneFormatVo != null && sceneName != "")
        {
            //卸载子场景
            if (subSceneList.Count > 0)
            {
                foreach (string subName in subSceneList)
                {
                    SceneManager.UnloadSceneAsync(subName);
                }
                subSceneList.Clear();
            }

            //卸载ab
            if (sceneABList.Count > 0)
            {
                GameManager.instance.resourceManager.RemoveAssetBundle(sceneABList, true);
                sceneABList.Clear();
            }
            sceneFormatVo = null;
            sceneName = "";
        }
    }

    //加载场景
    public void LoadScene(string _sceneName,Vector3 _defPos)
    {
        InitScene();

        if (isLoadMainScene || isLoadSubScene) return;

        if (sceneName == _sceneName)
        {
            UpdatePos(_defPos);
            return;
        }

        UnLoadScene();

        isLoadMainScene = true;

        sceneName = _sceneName;

        defPos = _defPos;

        //获得场景依赖
        string sceneABPath = AppConst.GetSceneAssetBundlePath(sceneName);
        sceneABList.Add(sceneABPath);
        sceneABList.AddRange(SceneGlobalManifest.GetDirectDependencies(sceneABPath));

        //加载所有需要的ab
        GameManager.instance.resourceManager.LoadAssetBundle(sceneABList,
            (float progress) =>
            {
                GameManager.instance.windowManager.ShowLoadingUI("正在加载场景AB!", progress);
            },
            () =>
            {
                GameManager.instance.windowManager.HideLoadingUI();
                StartCoroutine(StartLoadScene());
            }
        );
    }

    /// <summary>
    /// 开始加载主场景
    /// </summary>
    /// <returns>The load scene.</returns>
    IEnumerator StartLoadScene(){

        configSceneName = sceneName.ToLower() + "_config";

        //加载配置场景
        AsyncOperation asyncoperation = SceneManager.LoadSceneAsync(configSceneName, LoadSceneMode.Additive);

        while (!asyncoperation.isDone)
        {
            GameManager.instance.windowManager.ShowLoadingUI("正在加载主场景!", asyncoperation.progress);
            yield return asyncoperation;
        }
        GameManager.instance.windowManager.HideLoadingUI();
        subSceneList.Add(configSceneName);

        if (SceneFormatVo.instance != null)
        {
            sceneFormatVo = SceneFormatVo.instance;
            isLoadMainScene = false;
            UpdatePos(defPos);
        }
    }

	/// <summary>
	/// 根据坐标更新场景
	/// </summary>
	/// <param name="pos">Position.</param>
    private void UpdatePos(Vector3 pos)
    {
        if (sceneFormatVo == null) return;

        if (isLoadSubScene) return;

        isLoadSubScene = true;

        //需要加载的场景名
        List<string> needLoadSceneNameList = SceneTool.GetNeedLoadScene(pos,sceneFormatVo);
        //已经加载过的场景名
        List<string> loadCompletetNameList = new List<string>();

        //将已经加载过的剔除掉
        for (int i = needLoadSceneNameList.Count - 1; i > -1; i--)
        {
            if (subSceneList.IndexOf(needLoadSceneNameList[i]) > -1)
            {
                loadCompletetNameList.Add(needLoadSceneNameList[i]);
                needLoadSceneNameList.RemoveAt(i);
            }
        }

        //卸载不需要的场景
        for (int i = subSceneList.Count - 1; i > -1; i--)
        {
            string sceneName = subSceneList[i];
            if (sceneName != configSceneName && needLoadSceneNameList.IndexOf(sceneName) == -1 && loadCompletetNameList.IndexOf(sceneName) == -1)
            {
                subSceneList.RemoveAt(i);
                SceneManager.UnloadSceneAsync(sceneName);
            }
        }
        if (needLoadSceneNameList.Count > 0)
            StartCoroutine(StartLoadSubScene(needLoadSceneNameList));
        else
            isLoadSubScene = false;
    }

    //开始加载子场景
    IEnumerator StartLoadSubScene(List<string> sceneNameList)
    {

        float needLoad = (float)sceneNameList.Count;
        float current = 0;

        if (needLoad > 0)
        {
            foreach (string sceneName in sceneNameList)
            {
                //加载配置场景
                AsyncOperation asyncoperation = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);

                while (!asyncoperation.isDone)
                {

                    //GameManager.instance.windowManager.ShowLoadingUI(string.Format("正在加载子场景{0}/{1}!", current, needLoad), asyncoperation.progress);
                    yield return asyncoperation;
                }
                subSceneList.Add(sceneName);
                current++;
                if (current == needLoad)
                {
                    isLoadSubScene = false;
                   // GameManager.instance.windowManager.HideLoadingUI();
                }
            }
        }
        else
        {
            isLoadSubScene = false;
        }

    }


}
